package com.java.study;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author xuyuansheng
 */
@RestController
public class Publisher {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @RequestMapping("publishMessage")
    public Object publishMessage(@RequestBody JSONObject msg) {
        rabbitTemplate.convertAndSend("exchangeName", "bindingKey", msg, (message -> {
            message.getMessageProperties().setDelay(msg.getIntValue("delay"));
            return message;
        }));
        return "null";
    }

    @RabbitListener(ackMode = "NONE", replyPostProcessor = "replyPost",
            bindings = {@QueueBinding(key = "bindingKey",/*  绑定名称，也就是路由Key */
                    value = @Queue(value = "queueName", autoDelete = "true"), /*  队列 */
                    exchange = @Exchange(value = "exchangeName", autoDelete = "true", delayed = "true")) /*  交换机 */
            })
    public void listener(@Headers Map<String, Object> headers,
                         @Payload Map<String, Object> msg) {
        if (ObjectUtils.nullSafeEquals(true, msg.get("exception"))) {
            throw new RuntimeException("异常提交吗?");
        }
        System.out.println(msg);
        System.out.println(headers);
    }

}
